/*
 * BanBu_CollectionController
 * @description 本文件提供我收藏的表情界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供我收藏的表情界面的ViewController
 */

#import "BanBu_CollectionController.h"
#import "BanBu_CollectionCell.h"
#import "BanBu_EmoManger.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "BanBu_SmileViewAPI.h"
#import "BanBu_ImageView.h"
#import "BanBu_EmoKeyboard.h"
#import "BanBu_ChatViewController.h"
#import "UIViewController+Animation.h"
#import "CJSONSerializer.h"

@interface BanBu_CollectionController ()

@end

@implementation BanBu_CollectionController


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_collectionTable release],_collectionTable = nil;
    [_collEmoArr release],_collEmoArr = nil;
    [_deleteButton release];
    [_editView release];
    [_selectedEmoDic release];
    [_selectedEmoArr release];
    
    [super dealloc];
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"collectedEmo", nil);
    self.collectionTable.backgroundColor = [UIColor clearColor];
    BanBu_ImageView *img = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    self.view.backgroundColor = [UIColor colorWithPatternImage:img.image];
    self.collectionTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self createEditButton];
    
    
    self.selectedEmoArr = [NSMutableArray arrayWithCapacity:8];
    self.selectedEmoDic = [NSMutableDictionary dictionaryWithCapacity:8];
    _collEmoArr = [[NSMutableArray alloc]initWithCapacity:10];
    [self getCollectionInfo];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshCollectedEmo) name:KRefreshCollectedEmo object:nil];
}

#pragma mark - 重新获取到收藏数据，刷新收藏的表情

- (void)refreshCollectedEmo
{
    NSLog(@"刷新收藏表情");
    [self getCollectionInfo];
    [self.collectionTable reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload
{
    [self setDeleteButton:nil];
    [self setEditView:nil];
    [self setCollectionTable:nil];
    [super viewDidUnload];
}

//获取收藏的表情信息
-(void)getCollectionInfo
{
    NSMutableDictionary * collectedEmoDic = [[NSMutableDictionary alloc]initWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithFile:CollectEmoInfoPath]];
    
    NSMutableArray * array = [[NSMutableArray alloc] initWithArray:collectedEmoDic.allValues];
    
    [array sortUsingFunction:compare context:NULL];
    [self.collEmoArr removeAllObjects];
    
    [self.collEmoArr addObjectsFromArray:array];
    NSInteger index = [[[array lastObject] valueForKey:KeyIndex] integerValue];
    
    [array release];
    [collectedEmoDic release];
    
    //加最后一个添加按钮
    NSDictionary * addButton = [NSDictionary dictionaryWithObjectsAndKeys:@"20140101000000",KeyName,@"localhost",KeyPath,[NSNumber numberWithInteger:index+1],KeyIndex,@"png",KeyExtension, nil];
    
    [self.collEmoArr addObject:addButton];
}

//编辑按钮
-(void)createEditButton
{
    //添加“删除”按钮
    _editButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    _editButton.position = ButtonPositionRight;
    [_editButton.titleLabel setFont:[UIFont systemFontOfSize:16]];
    
    CGFloat btnLen1 = [NSLocalizedString(@"editButton", nil) sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(150, 30)].width;
    _editButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
    _editButton.tag = 101;
    [_editButton addTarget:self action:@selector(setEditing:animated:) forControlEvents:UIControlEventTouchUpInside];
    [_editButton setTitle:NSLocalizedString(@"editButton", nil) forState:UIControlStateNormal];
    UIBarButtonItem *delItem = [[[UIBarButtonItem alloc] initWithCustomView:_editButton] autorelease];
    self.navigationItem.rightBarButtonItem = delItem;
}

-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:!self.editing animated:YES];
    
    _editView.hidden = !_editView.hidden;
    if (_editView.hidden == NO)
    {
        CGFloat btnLen1 = [NSLocalizedString(@"cancelNotice", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
        _editButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
        [_editButton setTitle:NSLocalizedString(@"cancelNotice", nil)  forState:UIControlStateNormal];
        
        [_deleteButton setTitle:NSLocalizedString(@"deleteButton", nil) forState:UIControlStateNormal];
        
        _deleteButton.enabled = NO;
        
        [[NSNotificationCenter defaultCenter] postNotificationName:KSetAddButtonHidden object:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"hidden", nil]];
    }
    else
    {
        CGFloat btnLen1 = [NSLocalizedString(@"editButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
        _editButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
        [_editButton setTitle:NSLocalizedString(@"editButton", nil) forState:UIControlStateNormal];
        _deleteButton.enabled = YES;
        
        [self.collectionTable reloadData];
        
        [self.selectedEmoArr removeAllObjects];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:KSetAddButtonHidden object:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO],@"hidden", nil]];
    }
}


#pragma mark - TableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return ceil(_collEmoArr.count/4.0);
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdentifier = @"collectioncell";
    BanBu_CollectionCell * cell = (BanBu_CollectionCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil)
    {
        NSArray * objects =[[NSBundle mainBundle]loadNibNamed:@"BanBu_CollectionCell" owner:self options:nil];
        
        for (id object in objects)
        {
            if ([object isMemberOfClass:[BanBu_CollectionCell class]])
            {
                cell = object;
                cell.backgroundColor = [UIColor clearColor];
                break;
            }
        }
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    NSMutableDictionary * collectionDic= [NSMutableDictionary dictionaryWithCapacity:4];
    
    if (_collEmoArr.count > indexPath.row * 4 + 3)
    {
        [collectionDic setValue:[_collEmoArr objectAtIndex:indexPath.row * 4 + 3] forKey:@"4"];
        [collectionDic setValue:[_collEmoArr objectAtIndex:indexPath.row * 4 + 2] forKey:@"3"];
        [collectionDic setValue:[_collEmoArr objectAtIndex:indexPath.row * 4 + 1] forKey:@"2"];
        [collectionDic setValue:[_collEmoArr objectAtIndex:indexPath.row * 4] forKey:@"1"];
    }
    else if (_collEmoArr.count > indexPath.row * 4 + 2)
    {
        [collectionDic setValue:[_collEmoArr objectAtIndex:indexPath.row * 4 + 2] forKey:@"3"];
        [collectionDic setValue:[_collEmoArr objectAtIndex:indexPath.row * 4 + 1] forKey:@"2"];
        [collectionDic setValue:[_collEmoArr objectAtIndex:indexPath.row * 4] forKey:@"1"];
    }
    else if (_collEmoArr.count > indexPath.row * 4 + 1)
    {
        [collectionDic setValue:[_collEmoArr objectAtIndex:indexPath.row * 4 + 1] forKey:@"2"];
        [collectionDic setValue:[_collEmoArr objectAtIndex:indexPath.row * 4] forKey:@"1"];
    }
    else if (_collEmoArr.count > indexPath.row * 4)
    {
        [collectionDic setValue:[_collEmoArr objectAtIndex:indexPath.row * 4] forKey:@"1"];
    }
    
    [cell setAllInfo:collectionDic];
    
    [cell setSelectedOrNot:self.selectedEmoDic];
    
    return cell;
}


#pragma mark - 添加、删除收藏的表情
//设置选中
-(void)setSelectedView:(BanBu_CollectionImageView *)collectView withCell:(BanBu_CollectionCell *)cell
{
    if (!_editView.hidden)
    {
        _deleteButton.enabled = YES;
        
        UIImageView * imageView = (UIImageView *)[cell viewWithTag:collectView.index];
        
        imageView.hidden = !imageView.hidden;
        
        if (!imageView.hidden)
        {
            if ([collectView.imageInfoDic valueForKey:KeyFavid])
            {
                [self.selectedEmoArr addObject:[collectView.imageInfoDic valueForKey:KeyFavid]];
                [self.selectedEmoDic setValue:[NSNumber numberWithBool:YES] forKey:[collectView.imageInfoDic valueForKey:KeyFavid]];
            }
        }
        else
        {
            if ([collectView.imageInfoDic valueForKey:KeyFavid])
            {
                [self.selectedEmoArr removeObject:[collectView.imageInfoDic valueForKey:KeyFavid]];
                [self.selectedEmoDic setValue:[NSNumber numberWithBool:NO] forKey:[collectView.imageInfoDic valueForKey:KeyFavid]];
            }
           
        }
        
        NSString * title = NSLocalizedString(@"deleteButton", nil);
        if (self.selectedEmoArr.count)
        {
            title = [NSString stringWithFormat:@"%@(%d)",NSLocalizedString(@"deleteButton", nil),self.selectedEmoArr.count];
        }
        
        [_deleteButton setTitle:title forState:UIControlStateNormal];
    }
}

-(BOOL)isEditing
{
    if (self.editView.hidden == NO)
    {
        [self.selectedEmoArr removeAllObjects];
        [self.selectedEmoDic removeAllObjects];
        [_collectionTable reloadData];
        return YES;
    }
    else
    {
        return NO;
    }
}

//删除收藏的表情
- (IBAction)deleteCollectedEmo:(UIButton *)sender
{
    if (self.selectedEmoArr.count)
    {
        //删除表情
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            //提交服务器，删除表情
            NSDictionary * parDic = [NSDictionary dictionaryWithObjectsAndKeys:[self.selectedEmoArr componentsJoinedByString:@","],@"favid", nil];
            [AppComManager getBanBuDataWIthCollectEmo:BanBu_DelCollectEmo_ByUser par:parDic delegate:MyAppDataManager];
            //归档收藏的表情
            NSMutableDictionary * collectedEmoDic = [[NSMutableDictionary alloc]initWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithFile:CollectEmoInfoPath]];
            
            [collectedEmoDic removeObjectsForKeys:self.selectedEmoArr];
            
            [NSKeyedArchiver archiveRootObject:collectedEmoDic toFile:CollectEmoInfoPath];
            
            [collectedEmoDic release];
            
            dispatch_sync(dispatch_get_main_queue(), ^{
                
                [self getCollectionInfo];
                [self.selectedEmoArr removeAllObjects];
                [self.selectedEmoDic removeAllObjects];
                self.editView.hidden = YES;
                [_collectionTable reloadData];

                [self.collectionTable reloadData];
                
                NSString * title = NSLocalizedString(@"deleteButton", nil);
                [_deleteButton setTitle:title forState:UIControlStateNormal];
           
                //刷新收藏的表情键盘
                [[NSNotificationCenter defaultCenter]postNotificationName:KRefreshCollectedEmo object:nil];
                
                //修改“完成”按钮
                CGFloat btnLen1 = [NSLocalizedString(@"finishButton", nil) sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(150, 30)].width;
                _editButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
                [_editButton setTitle:NSLocalizedString(@"finishButton", nil) forState:UIControlStateNormal];
            });
        });
    }
    else
    {
        [self.selectedEmoArr removeAllObjects];
        [self.selectedEmoDic removeAllObjects];
        self.editView.hidden = YES;
        [_collectionTable reloadData];
    }
}

//添加收藏的表情
-(void)addCollectedEmo:(BanBu_CollectionImageView *)collectView
{
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [picker setAllowsEditing:YES];
    [self presentViewController:picker animated:YES];
    [picker release];
}

//获取到图片后
- (void)imagePickerController:(UIImagePickerController *)picker
        didFinishPickingImage:(UIImage *)image
                  editingInfo:(NSDictionary *)editingInfoo
{
    //图片的路径，判断重复
    NSString * imageUrl = [NSString stringWithFormat:@"%@",[editingInfoo valueForKey:UIImagePickerControllerReferenceURL]];
    
    //2014年11月04日10:16:32 by yinlinlin 判断是否收藏过，防止重复收藏
    for (NSDictionary * collectDict in self.collEmoArr)
    {
        NSLog(@"%@",collectDict);
        if ([[collectDict valueForKey:KeyLocalUrl] isEqualToString:imageUrl])
        {
            [picker dismissModalViewControllerAnimated:YES];
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"re_collect", nil) activityAnimated:NO duration:1.2f];
            return;
        }
    }
    NSData *data = nil;
    
    if (image.size.width>1500 || image.size.height>1500)
    {
        image = [MyAppDataManager scaleImage:image proportion:3];
    }
    else if (image.size.width>1000 || image.size.height > 1000)
    {
        image = [MyAppDataManager scaleImage:image proportion:2];
    }
    
    data = UIImageJPEGRepresentation(image, 0.7);
    if(data.length>100*1024)
    {
        NSData * date1 = nil;
        date1 = UIImageJPEGRepresentation(image, 0.6);
        data = date1;
    }
    
    //将图片转移到收藏文件夹
    [self collectCustImage:data withUrl:imageUrl];
    [self getCollectionInfo];
    [self.collectionTable reloadData];
    [picker dismissModalViewControllerAnimated:YES];
}

//收藏图片
-(void)collectCustImage:(NSData *)imageData withUrl:(NSString *)url
{
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"uploading", nil) activityAnimated:YES];
    //将图片复制到收藏文件夹CollectionFolder
    NSDictionary * amsg = nil;
    
    //获取收藏的表情信息
    NSMutableDictionary * collectedEmoDic = [[NSMutableDictionary alloc]initWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithFile:CollectEmoInfoPath]];
    NSMutableArray *  collectedEmoArr = [[NSMutableArray alloc]initWithArray:collectedEmoDic.allValues];
    
    //排序
    [collectedEmoArr sortUsingFunction:compare context:NULL];
    
    //本次收藏的表情
    NSMutableDictionary * emoDic = [NSMutableDictionary dictionaryWithCapacity:5];
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString * name = [formatter stringFromDate:[NSDate date]];
    
    NSString * imagePath = [AppComManager pathForEmo:name withFolder:CollectionFolder];
    [FileManager createFileAtPath:imagePath contents:imageData attributes:nil];
    
    [emoDic setValue:[amsg valueForKey:KeyChatid] forKey:Keyid];
    [emoDic setValue:name forKey:KeyName];
    [emoDic setValue:[amsg valueForKey:KeyContent] forKey:KeyPath];
    //2014年08月19日11:40:53,添加url，防止重复收藏
    [emoDic setValue:url forKey:KeyLocalUrl];
    
    
    //索引
    NSInteger index = [[[collectedEmoArr lastObject] valueForKey:KeyIndex] integerValue]+1;
    [emoDic setValue:[NSNumber numberWithInteger:index] forKey:KeyIndex];
    
    //后缀
    NSString * extension = @"jpg";
    [emoDic setValue:extension forKey:KeyExtension];
    
    //归档
    [collectedEmoDic setValue:emoDic forKey:name];
    [NSKeyedArchiver archiveRootObject:collectedEmoDic toFile:CollectEmoInfoPath];
        
    [emoDic setValue:extension forKey:@"extname"];
    
    [formatter release];
    [collectedEmoDic release];

    //将图片上传到服务器
    [AppComManager uploadCollectedEmo:imageData mediaName:[NSString stringWithFormat:@"%@.jpg",name] par:emoDic delegate:self];
    self.navigationController.view.userInteractionEnabled = NO;
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES];
}

-(void)banbuUploadRequest:(NSDictionary *)resDic didFinishedWithError:(NSError *)error
{
    self.navigationController.view.userInteractionEnabled = YES;
    if ([[resDic valueForKey:@"ok"] boolValue])
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"uploadSucceed", nil) activityAnimated:NO duration:1.2f];
        
        //表情名
        NSString * path =[resDic valueForKey:@"fileurl"];
        NSMutableDictionary * emoDic = [NSMutableDictionary dictionaryWithCapacity:5];
        [emoDic setValue:path forKey:KeyPath];
        [emoDic setValue:[resDic valueForKey:KeyName] forKey:KeyName];
        [emoDic setValue:[resDic valueForKey:KeyIndex] forKey:KeyIndex];
        [emoDic setValue:[resDic valueForKey:KeyExtension] forKey:KeyExtension];
        [emoDic setValue:[resDic valueForKey:Keyid] forKey:Keyid];
        [emoDic setValue:[resDic valueForKey:KeyLocalUrl] forKey:KeyLocalUrl];
        NSString * contentPath = [AppComManager pathForCollect:path];
        NSString * imagePath = [AppComManager pathForEmo:[emoDic valueForKey:KeyName] withFolder:CollectionFolder];
        
        [FileManager copyItemAtPath:imagePath toPath:contentPath error:nil];
        
        //提交服务器保存
        NSMutableDictionary * collectedEmoDic = [NSMutableDictionary dictionaryWithCapacity:2];
        
        NSString *content = [[CJSONSerializer serializer] serializeDictionary:emoDic];
        content = [[content dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        
        [collectedEmoDic setValue:content forKey:KeyContent];
        [AppComManager getBanBuDataWIthCollectEmo:BanBu_AddCollectEmo_ByUser par:collectedEmoDic delegate:MyAppDataManager];
    }
    else
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"uploadFailNotice", nil) activityAnimated:NO duration:1.2f];
    }
}
@end
